package com.ybwh.springboot2.controller;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.ybwh.springboot2.common.RespData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 调整线上日志级别的接口，用于线上问题定位
 * </p>
 *
 * @author fanbeibei
 * @version V1.0
 * @since 2019/7/3 10:50
 */
@RestController
@Slf4j
@RequestMapping("/")
public class LogController {


    @GetMapping("/log")
    public RespData<String> log(@RequestParam("packageName") String packageName) {
        System.out.println("----------------------------------------------------------");
        log.error("error -- hello");
        log.warn("warn -- hello");
        log.info("info -- hello");
        log.debug("debug -- hello");
        System.out.println("----------------------------------------------------------");
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Level logLevel = loggerContext.getLogger(packageName).getLevel();
        return RespData.successResp(logLevel.toString());
    }

    @GetMapping("/changeLog")
    public RespData<String> changeLog(@RequestParam("packageName") String packageName,
                                      @RequestParam("logLevel") String logLevel) {
        try {
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            loggerContext.getLogger(packageName).setLevel(Level.valueOf(logLevel));
        } catch (Exception e) {
            log.error("动态修改日志级别出错，原因：" + e.getMessage(), e);
            return RespData.failedResp(ExceptionUtils.getStackTrace(e));
        }
        return RespData.successResp(null);
    }

}
